/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.ormlite;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.table.DatabaseTableConfig;
import net.apexes.commons.lang.Checks;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * 
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 */
public interface DatabaseHelper extends AutoCloseable {
    
    /**
     * 获取指定表的Dao对象
     * @param table 表
     * @return
     * @throws SQLException
     */
    <T, ID> Dao<T, ID> dao(Table<T> table) throws SQLException;

    /**
     * 在同一个数据库事务中执行操作
     * @param callable 包装要执行的操作
     * @return
     * @throws Exception
     */
    <E> E callInTransaction(Callable<E> callable) throws Exception;

    /**
     *
     * @return
     */
    ChangeSupportable getChangeSupportable();
        
    /**
     * 
     * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
     *
     */
    class Registry {

        public static void register(Table<?>... tables) {
            register(Arrays.asList(tables));
        }

        public static void register(List<Table<?>> tables) {
            Checks.verifyNotNull(tables, "tables");
            List<DatabaseTableConfig<?>> configs = new ArrayList<>();
            for (Table<?> table : tables) {
                configs.add(table.config());
            }
            DaoManager.addCachedDatabaseConfigs(configs);
        }
    }
    
    /**
     * 
     * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
     *
     */
    interface ChangeSupportable {
        
        void addChange(Table<?> table);
        
        boolean isChange();
        
        void clearChange();
        
        void notifyChange();
        
    }
    
}
